package com.ttg.web.service.Impl;


import cn.hutool.core.util.ZipUtil;
import com.ttg.common.entities.RattingTask;
import com.ttg.common.enums.ErrorCodeEnums;
import com.ttg.common.enums.TaskEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.sftp.FtpProperties;
import com.ttg.common.sftp.FtpUtils;
import com.ttg.common.utils.CommUtils;
import com.ttg.common.utils.DateTimeUtil;
import com.ttg.common.utils.sm.GmUtils;
import com.ttg.model.dto.*;
import com.ttg.model.pojo.VipBankInfo;
import com.ttg.model.pojo.VipBindAccount;
import com.ttg.model.pojo.VipInfo;
import com.ttg.web.dao.VipBankInfoDao;
import com.ttg.web.dao.VipBindAccountDao;
import com.ttg.web.dao.VipInfoDao;
import com.ttg.web.service.ManageTagInfoService;
import com.ttg.web.service.VipBankInfoOriginalService;
import com.ttg.web.service.VipBankInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;


/**
 * @author zhangHongYuan
 * @description
 * @date 2023/6/8 11:19
 */
@Service
@Slf4j
public class VipBankInfoServiceImpl implements VipBankInfoService {

    @Autowired
    private VipBankInfoDao vipBankInfoDao;

    @Autowired
    private VipBindAccountDao vipBindAccountDao;

    @Autowired
    private VipInfoDao vipInfoDao;

    @Autowired
    private ManageTagInfoService manageTagInfoService;

    @Override
    public void getBankInfoByExcelByPrivate() {
        //todo 每日文件名生成
        String filePathByPrivate = "D:\\Users\\user\\Desktop\\文件添加测试数据\\对私数据表.xls";
        manageTagInfoService.getDataByFileTwo(filePathByPrivate, 1);
    }

    @Override
    public void getBankInfoByExcelByPublic() {
        //todo 每日文件名生成
        String filePathByPublic = "D:\\Users\\user\\Desktop\\文件添加测试数据\\收单商户数据表.xls";
        manageTagInfoService.getDataByFileTwo(filePathByPublic, 2);
    }

    @Override
    public void getBankInfoByExcelTwo() {
        manageTagInfoService.getDataByFile("", 1);
    }

    @Override
    public void getBankInfo(GetBankInfoDto dto) {
        List<VipInfo> list = null;
        if (Objects.isNull(dto) || CollectionUtils.isEmpty(dto.getVipId())) {
            list = vipInfoDao.allByStatus();
        } else {
            list = vipInfoDao.QueryByIdsAndStatus(dto.getVipId());
        }
        for (VipInfo vipInfo : list) {
            //获取账号号
            VipDetailDto vipDetailDto = new VipDetailDto();
            List<VipBindAccount> vipBindAccount = vipBindAccountDao.getVipBindAccount(vipDetailDto);
            for (VipBindAccount bindAccount : vipBindAccount) {
                //todo 向银行银行请求数据

                BankMemberGradeDto bankMemberGradeDto = new BankMemberGradeDto();
                BankMemberGradeDto2 bankMemberGradeDto2 = new BankMemberGradeDto2();
                VipBankInfo vipBankInfo = new VipBankInfo();
                vipBankInfo.setLbls(Arrays.toString(bankMemberGradeDto.getLbls()));
                vipBankInfo.setCstId(bankMemberGradeDto.getCstId());
                vipBankInfo.setCstName(bankMemberGradeDto.getCstName());
                vipBankInfo.setCrdtNo(bankMemberGradeDto.getCrdtNo());
                vipBankInfo.setCstGrdCd(bankMemberGradeDto.getCstGrdCd());
                vipBankInfo.setDmdepBal(new BigDecimal(bankMemberGradeDto2.getDmdepBal()));
                vipBankInfo.setTmdepBal(new BigDecimal(bankMemberGradeDto2.getTmdepBal()));
                vipBankInfo.setLoanBal(new BigDecimal(bankMemberGradeDto2.getLoanBal()));
                vipBankInfo.setChrtcBal(new BigDecimal(bankMemberGradeDto2.getChrtcBal()));
                vipBankInfo.setShrAmtBal(new BigDecimal(bankMemberGradeDto2.getShrAmtBal()));
                vipBankInfo.setCrCrdBillAmt(new BigDecimal(bankMemberGradeDto2.getCrCrdBillAmt()));
                vipBankInfo.setVipId(vipInfo.getVipId());
                vipBankInfo.setTime(LocalDate.now());
                vipBankInfo.setBankCarNo(Long.valueOf(bindAccount.getBankAccount()));
                VipBankInfo byAmountAndDate = vipBankInfoDao.getByAmountAndDate(bindAccount.getBankAccount(), LocalDate.now());
                if (Objects.nonNull(byAmountAndDate)) {
                    vipBankInfo.setVipId(byAmountAndDate.getVipId());
                }
                vipBankInfoDao.saveOrUpdate(vipBankInfo);
            }


        }

    }


    @Value("${sftp.localPath}")
    private String localPath;

    @Value("${sftp.remotePath}")
    private String remotePath;

    @Value("${sftp.type}")
    private String type;

    @Value("${sftp.port}")
    private Integer port;

    @Value("${sftp.userName}")
    private String userName;

    @Value("${sftp.passWord}")
    private String passWord;

    @Value("${sftp.ip}")
    private String ip;

    @Value("${sftp.zipFilePrefix}")
    private String zipFilePrefix;


    @Value("${sftp.yxRemotePath}")
    private String yxRemotePath;

    @Value("${sftp.yxZipFilePrefix}")
    private String yxZipFilePrefix;

    @Autowired
    private VipBankInfoOriginalService vipBankInfoOriginalService;

    @Override
    @RattingTask(taskEnum = TaskEnum.GET_BANK_INFO_BY_UNL)
    public void getBankInfoByUnl(TaskGetBankInfoDTO reqDto) {
        String s;
        String d;
        if (Objects.nonNull(reqDto) && StringUtils.isNotBlank(reqDto.getDate())) {
            LocalDate localDate = null;
            try {
                localDate = DateTimeUtil.strToDateYYYY_MM_DD(reqDto.getDate());
                s = DateTimeUtil.formatYYYYMMDD(localDate);
                d = DateTimeUtil.formatYYYYMMDD(localDate.minusMonths(1));
            } catch (Exception e) {
                log.error("传入日期有误" + reqDto.getDate());
                return;
            }
        } else {
            LocalDate localDate = DateTimeUtil.getYesterday000().toLocalDate();
            s = DateTimeUtil.formatYYYYMMDD(localDate);
            d = DateTimeUtil.formatYYYYMMDD(localDate.minusMonths(1));
        }
        if (StringUtils.isBlank(localPath)) {
            throw new BaseException(ErrorCodeEnums.BANK_GET_FILE_PATH_ERROR);
        }
        if (reqDto.isPassFtp()) {
            log.info("跳过SFTP取文件,直接开始解析");
        } else {
            log.info("开始从SFTP取文件");
            String remoteFilename = zipFilePrefix + s + ".ok";
            String dRemoteFilename = zipFilePrefix + d + ".ok";
            String localFileName = zipFilePrefix + s + ".ok";
            FtpProperties ftpProperties = new FtpProperties();
            ftpProperties.setType(type);
            ftpProperties.setPort(port);
            ftpProperties.setUsername(userName);
            ftpProperties.setPassword(GmUtils.sm4ECBDecrypt(passWord));
            ftpProperties.setServerIp(ip);
            File okFile=null;
            File zipFile=null;
            if (Objects.isNull(reqDto.getZipType())||reqDto.getZipType()==0){
                FtpUtils.download(ftpProperties, remotePath, remoteFilename, localPath, localFileName);
                FtpUtils.delete(ftpProperties, remotePath, dRemoteFilename);
                okFile = new File(CommUtils.filePathFilterClean(localPath + localFileName));
                if (!okFile.exists()) {
                    throw new BaseException(ErrorCodeEnums.BANK_OK_FILE_NOT_EXISTS);
                }
                remoteFilename = zipFilePrefix + s + ".zip";
                localFileName = zipFilePrefix + s + ".zip";
                dRemoteFilename = zipFilePrefix + d + ".zip";
                FtpUtils.download(ftpProperties, remotePath, remoteFilename, localPath, localFileName);
                FtpUtils.delete(ftpProperties, remotePath, dRemoteFilename);
                zipFile = new File(CommUtils.filePathFilterClean(localPath + localFileName));
                if (!zipFile.exists()) {
                    throw new BaseException(ErrorCodeEnums.BANK_ZIP_FILE_NOT_EXISTS);
                }
                ZipUtil.unzip(localPath + localFileName, localPath + zipFilePrefix + s + File.separator);
            }
            if (Objects.isNull(reqDto.getZipType())||reqDto.getZipType()==1) {

                localFileName = yxZipFilePrefix + s + ".ok";
                remoteFilename = yxZipFilePrefix + s + ".ok";

                FtpUtils.download(ftpProperties, yxRemotePath, remoteFilename, localPath, localFileName);
                okFile = new File(CommUtils.filePathFilterClean(localPath + localFileName));
                if (!okFile.exists()) {
                    throw new BaseException(ErrorCodeEnums.BANK_OK_FILE_NOT_EXISTS);
                }

                localFileName = yxZipFilePrefix + s + ".zip";
                remoteFilename = yxZipFilePrefix + s + ".zip";

                FtpUtils.download(ftpProperties, yxRemotePath, remoteFilename, localPath, localFileName);
                zipFile = new File(CommUtils.filePathFilterClean(localPath + localFileName));
                if (!zipFile.exists()) {
                    throw new BaseException(ErrorCodeEnums.BANK_ZIP_FILE_NOT_EXISTS);
                }
                ZipUtil.unzip(localPath + localFileName, localPath + yxZipFilePrefix + s + File.separator);
            }
        }
        boolean succ = true;
        BaseException te = null;
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_agent".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_agent")) {
            try {
                vipBankInfoOriginalService.bankAgent(localPath + zipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 bankAgent 异常", e);
                succ = false;
            }
        }
/*        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_public_primitive_aum".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_public_primitive_aum")) {
            try {
                vipBankInfoOriginalService.bankPublicPrimitiveAum(localPath + zipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 bankAgent 异常", e);
                succ = false;
            }
        }*/


        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_card_data_info".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_card_data_info")) {
            try {
                vipBankInfoOriginalService.cardDataUpdate(localPath + zipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 cardDataUpdate 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_customer_sign_info".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_customer_sign_info")) {
            try {
                vipBankInfoOriginalService.customerSignUpdate(localPath + zipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 customerSignUpdate 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_product_data_info".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_product_data_info")) {
            try {
                vipBankInfoOriginalService.productDataInfo(localPath + zipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 productDataInfo 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_public_primitive".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_public_primitive")) {
            try {
                vipBankInfoOriginalService.merchantInfoUpdate(localPath + zipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 merchantInfoUpdate 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_public_trade_primitive".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_public_trade_primitive")) {
            try {
                vipBankInfoOriginalService.merchantTradeInfo(localPath + zipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 merchantTradeInfo 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_card_binding_info".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_card_binding_info")) {
            try {
                vipBankInfoOriginalService.bankCardBindingInfoUpdate(localPath + zipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 bankCardBindingInfoUpdate 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_private_primitive".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_private_primitive")) {
            try {
                vipBankInfoOriginalService.bankPrivatePrimitiveUpdate(localPath + zipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 bankPrivatePrimitiveUpdate 异常", e);
                succ = false;
            }
        }

        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_app_coupon_vip".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_app_coupon_vip")) {
            try {
                vipBankInfoOriginalService.vipInfoUpdate(localPath + yxZipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 vipInfoUpdate 异常", e);
                succ = false;
            }
        }


        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_qyyx_cust_aum".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_qyyx_cust_aum")) {
            try {
                vipBankInfoOriginalService.qyyxCustAumUpdate(localPath + yxZipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 qyyxCustAumUpdate 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_qyyx_cust_group".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_qyyx_cust_group")) {
            try {
                vipBankInfoOriginalService.qyyxCustGroupUpdate(localPath + yxZipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 qyyxCustGroupUpdate 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_qyyx_cust_sign_tag".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_qyyx_cust_sign_tag")) {
            try {
                vipBankInfoOriginalService.qyyxCustSignTagUpdate(localPath + yxZipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 qyyxCustSignTagUpdate 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_qyyx_deposit_account_detail".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_qyyx_deposit_account_detail")) {
            try {
                vipBankInfoOriginalService.qyyxDepositAccountDetailUpdate(localPath + yxZipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 qyyxDepositAccountDetailUpdate 异常", e);
                succ = false;
            }
        }
        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_qyyx_deposit_amount".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_qyyx_deposit_amount")) {
            try {
                vipBankInfoOriginalService.qyyxDepositAmountUpdate(localPath + yxZipFilePrefix + s + File.separator);
            } catch (BaseException e) {
                te = e;
                log.error("任务 qyyxDepositAmountUpdate 异常", e);
                succ = false;
            }
        }
//        if ((StringUtils.isBlank(reqDto.getJobName()) && CollectionUtils.isEmpty(reqDto.getJobNames())) || "tbl_bank_servic".equals(reqDto.getJobName()) || reqDto.getJobNames().contains("tbl_bank_servic")) {
//            try {
//                vipBankInfoOriginalService.bankServicUpdate(localPath + zipFilePrefix + s + File.separator);
//            } catch (BaseException e) {
//                te = e;
//                log.error("任务 bankServicUpdate 异常", e);
//                succ = false;
//            }
//        }

        if (!succ) {
            throw te;
        }
    }


}
